package com.spring.demo.core.job;

import org.quartz.Job;
import org.quartz.JobDetail;
import org.quartz.spi.TriggerFiredBundle;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.PropertyAccessorFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.scheduling.quartz.SpringBeanJobFactory;

/**
 * job factory，装配job
 * 
 * @author sean
 * 
 */
public class SpringQuartzJobFactory extends SpringBeanJobFactory {

	@Autowired
	private ApplicationContext applicationContext;
	private Logger logger = LoggerFactory.getLogger(getClass());

	@Override
	@SuppressWarnings("unchecked")
	protected Object createJobInstance(TriggerFiredBundle bundle)
			throws Exception {
		logger.debug("createJobInstance: "
				+ bundle.getJobDetail().getJobClass());

		// 从spring 容器获取job，这样@Autowired有效
		JobDetail jobDetail = bundle.getJobDetail();
		Job job = (Job) applicationContext.getBean(jobDetail.getJobClass());

		// 暂时没用，不知道如何设置jobDataMap。
		BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(job);
		MutablePropertyValues mpv = new MutablePropertyValues();
		mpv.addPropertyValues(jobDetail.getJobDataMap());
		mpv.addPropertyValues(bundle.getTrigger().getJobDataMap());
		bw.setPropertyValues(mpv);

		return job;
	}
}
